import * as Remote from '../services'
const TabsModel = {
    namespace: 'addressBar',
    state: {
        url:''
    },
    effects: {
        *openUrl({ payload }, { call, put }) {
            let ret = yield call(Remote.openUrl,payload);
            // yield put({
            //     type:'init',
            //     payload:{
            //         pages:ret.url
            //     }
            // });
            yield put({
                type:'tabs/updateTab',
                payload:{
                    windowId: ret.windowId,
                    title:ret.title,
                    url:ret.url
                }    
            })
        },
        *openDev({ payload }, { call, put }) {
            let ret = yield call(Remote.openDev,payload);
        },
        *capture({ payload }, { call, put }) {
            let ret = yield call(Remote.capture,payload);
        },
        *reload({ payload }, { call, put }) {
            let ret = yield call(Remote.reload,payload);
        },
        *navigate({ payload }, { call, put }) {
            let ret = yield call(Remote.navigate,payload);
            if (payload.role == 'goBack' || payload.role == 'goForward'){
                yield put({
                    type:'tabs/getPages'
                });    
            }
        },
    },
    reducers: {
        init(state, action) {
            return {
                url:action.payload.url
            };
        },
    },
    subscriptions: {
        urlChange({ dispatch, history }) {
            document.addEventListener('urlchange', (e) => {
                console.log('e.oldUrl',e)
                dispatch({type:"init",payload:{url:e.detail.url}}); 
                dispatch({
                    type:'tabs/updateTab',
                    payload:{
                        windowId: e.detail.windowId,
                        title:e.detail.title,
                        url:e.detail.url
                    }    
                })               
            });            
        }
    }
};

export default TabsModel;